package cn.tedu.overhaul.management.service.impl;

import cn.tedu.overhaul.management.config.IsDateInFormat;
import cn.tedu.overhaul.management.controller.OverhaulRentController;
import cn.tedu.overhaul.management.dto.persist.mapper.OverhaulMapper;
import cn.tedu.overhaul.management.dto.persist.mapper.OverhaulRentMapper;
import cn.tedu.overhaul.management.dto.persist.repository.IOverhaulRepository;
import cn.tedu.overhaul.management.pojo.dto.OverhaulMaintainAddNewDTO;
import cn.tedu.overhaul.management.pojo.dto.OverhaulMaintainUpdateDTO;
import cn.tedu.overhaul.management.pojo.dto.OverhaulRentAddNewDTO;
import cn.tedu.overhaul.management.pojo.entity.Overhaul;
import cn.tedu.overhaul.management.pojo.vo.*;
import cn.tedu.overhaul.management.service.IOverhaulService;
import cn.tedu.rtms.commons.ex.ServiceException;
import cn.tedu.rtms.commons.pojo.vo.PageData;
import cn.tedu.rtms.commons.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class OverhaulServiceImpl implements IOverhaulService {
    @Value("${overhaul.crud.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Autowired
    OverhaulMapper overhaulMapper;

    @Autowired
    IOverhaulRepository iOverhaulRepository;

    @Autowired
    OverhaulRentMapper overhaulRentMapper;

    @Autowired
    OverhaulRentController overhaulRentController;

    @Override
    public String addNew(OverhaulMaintainAddNewDTO overhaulAddNewDTO) {

        log.debug("开始处理[添加检修信息],参数:{}",overhaulAddNewDTO);

        //添加借用记录
        OverhaulRentAddNewDTO overhaulRentAddNewDTO=new OverhaulRentAddNewDTO();
        overhaulRentAddNewDTO.setName(overhaulAddNewDTO.getName());
        overhaulRentAddNewDTO.setTool(overhaulAddNewDTO.getTool());


        long toolNumberId2=Long.parseLong(overhaulRentAddNewDTO.getTool().get(1));
        String toolNumber2=overhaulMapper.selectToolNumber(toolNumberId2);
        int status= overhaulRentMapper.selectStatus(toolNumber2);
        if(status==2){
            String message ="借用工具失败，借用的工具正在使用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        overhaulRentController.addNew(overhaulRentAddNewDTO);
        //计算时长
        String str1 = overhaulAddNewDTO.getDuration().get(0);
        String str2 = overhaulAddNewDTO.getDuration().get(1);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = null;
        Date date2 = null;
        try {
            date1 = format.parse(str1);
            date2 = format.parse(str2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long diff = date2.getTime() - date1.getTime();
        //转换为分钟数
        long diffMinutes = TimeUnit.MILLISECONDS.toMinutes(diff);

        // 创建overhaulVO对象


        OverhaulVO overhaulVO=new OverhaulVO();
        Long id=overhaulRentMapper.selectByName(overhaulAddNewDTO.getName());
        if(id==null){
            //是:抛出异常
            String message ="检修人员不是用户,请输入合法的检修人员";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, message);
        }
        overhaulVO.setUserId(id);

        overhaulVO.setTime(LocalDateTime.now());
        //根据联机选择器返回的id值查询出工具名
        long toolNameId=Long.parseLong(overhaulAddNewDTO.getTool().get(0));
        String toolName=overhaulMapper.selectToolName(toolNameId);
        //根据联机选择器返回的id值查询出工具编号
        long toolNumberId=Long.parseLong(overhaulAddNewDTO.getTool().get(1));
        String toolNumber=overhaulMapper.selectToolNumber(toolNumberId);
        overhaulVO.setToolName(toolName);
        overhaulVO.setToolNumber(toolNumber);
        overhaulVO.setDurationStart(overhaulAddNewDTO.getDuration().get(0));
        overhaulVO.setDurationEnd(overhaulAddNewDTO.getDuration().get(1));
        overhaulVO.setDuration(diffMinutes);
        overhaulVO.setTarget(overhaulAddNewDTO.getTarget());
        overhaulVO.setContent(overhaulAddNewDTO.getContent());

        // 调用Mapper对象的insert()执行插入检修信息数据
        log.debug("即将执行插入数据,参数:{}",overhaulVO);
        overhaulMapper.insert(overhaulVO);

        return "200";
    }

    @Override
    public List<ToolNameVO> selectToolNumber() {
        log.debug("开始处理根据工具名称查出来所有型号");
        List<ToolNameVO> listName=overhaulMapper.selectListByTool();
        for (ToolNameVO toolNameVO : listName) {
            toolNameVO.setChildren(overhaulMapper.selectListByNumber(toolNameVO.getLabel()));
        }
        return listName;
    }

    @Override
    public PageData<MaintainVO> selectMaintain(Integer pageNum) {
        log.debug("开始处理【查询检修记录表】的业务，页码：{}", pageNum);
        PageData<MaintainVO> pageData=iOverhaulRepository.selectMaintain(pageNum,defaultQueryPageSize);
        return pageData;
    }

    @Override
    public PageData<MaintainVO> selectMaintain(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询检修记录表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageData<MaintainVO> pageData = iOverhaulRepository.selectMaintain(pageNum, pageSize);
        return pageData;
    }

    @Override
    public MaintainStandardNameVO getStandardById(Long id) {
        log.debug("开始处理【根据ID修改面板查询检修记录】的业务，参数：{}", id);
        MaintainStandardNameVO queryResult=iOverhaulRepository.getStandardById(id);

        if(queryResult==null){
            //是:抛出异常
            String message ="根据ID修改面板查询检修记录失败，根据ID修改面板查询检修记录不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return queryResult;
    }


    @Override
    public void updateInfoById(Long id, OverhaulMaintainUpdateDTO overhaulMaintainUpdateDTO) {
        log.debug("开始处理【修改检修记录】的业务，ID：{}，新数据：{}", id, overhaulMaintainUpdateDTO);
        MaintainStandardNameVO queryResult= iOverhaulRepository.getStandardById(id);
        if(queryResult==null){
            //是:抛出异常
            String message ="根据ID修改修改检修记录失败，根据ID修改的检修记录不存在！";
            log.warn(message);
        }


        //计算时长
        String str1 = overhaulMaintainUpdateDTO.getDurationStart();
        String str2 = overhaulMaintainUpdateDTO.getDurationEnd();
        String targetFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
        boolean isValidFormat = IsDateInFormat.isDateInFormat(str1,targetFormat);
        boolean isValidFormat2 = IsDateInFormat.isDateInFormat(str2,targetFormat);
        if(isValidFormat||isValidFormat2){
            // 解析原始日期字符串
            SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            Date date;
            Date date2;
            try {
                date = originalFormat.parse(str1);
                date2 = originalFormat.parse(str2);

                // 格式化日期为目标格式
                SimpleDateFormat targetFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String targetDate = targetFormat2.format(date);
                String targetDate2 = targetFormat2.format(date2);
                log.debug("原始日期: {},{}" , str1,str2);
                log.debug("目标日期: {},{}" , targetDate,targetDate2);
                str1=targetDate;
                str2=targetDate2;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = null;
        Date date2 = null;
        try {
            date1 = format.parse(str1);
            date2 = format.parse(str2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long diff = date2.getTime() - date1.getTime();
        //转换为分钟数
        long diffMinutes = TimeUnit.MILLISECONDS.toMinutes(diff);
        // 创建Overhaul对象
        OverhaulVO overhaulVO=new OverhaulVO();
        overhaulVO.setId(id);
        Long id2=overhaulRentMapper.selectByName(overhaulMaintainUpdateDTO.getName());
        if(id2==null){
            //是:抛出异常
            String message ="检修人员不是用户,请输入合法的检修人员";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_BAD_REQUEST, message);
        }
        overhaulVO.setUserId(id2);
        overhaulVO.setToolName(overhaulMaintainUpdateDTO.getToolName());
        overhaulVO.setToolNumber(overhaulMaintainUpdateDTO.getToolNumber());
        overhaulVO.setDurationStart(str1);
        overhaulVO.setDurationEnd(str2);
        overhaulVO.setDuration(diffMinutes);
        overhaulVO.setTarget(overhaulMaintainUpdateDTO.getTarget());
        overhaulVO.setContent(overhaulMaintainUpdateDTO.getContent());
        overhaulVO.setModificationTime(LocalDateTime.now());
        MaintainStandardVO selectFrequency=overhaulMapper.getStandardById(overhaulVO.getId());
        int frequency=0 ;
        if (selectFrequency.getModificationFrequency()!=null){
            frequency=selectFrequency.getModificationFrequency();
        }
        frequency++;
        log.debug("参数frequency:{}",frequency);
        overhaulVO.setModificationFrequency(frequency);
        iOverhaulRepository.update(overhaulVO);

    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据ID删除检修记录】的业务，参数：{}", id);
        // 调用Mapper对象的getStandardById()执行查询
        MaintainStandardNameVO queryResult=iOverhaulRepository.getStandardById(id);
        // 判断查询结果是否为null
        if (queryResult == null) {
            String message = "删除检修记录失败，尝试删除的检修记录数据不存在！";
            log.warn(message);
        }
        // 调用Mapper对象的deleteById()方法执行删除
        log.debug("即将执行删除，参数：{}", id);
        iOverhaulRepository.deleteById(id);
    }
}
